home *** CD-ROM | disk | FTP | other *** search
/ com!online 2005 May / com_0505_1.iso / opensource / top10 / currconv2-setup / currconv2-setup.exe / {app} / javascript / currencyFactory.js < prev    next >
Encoding:
JavaScript  |  2003-12-23  |  2.2 KB  |  92 lines

  1. /*
  2.   Copyright (c) 1999-2001 Alex Belgraver (http://www.belgraver.demon.nl)
  3.   Released part of the Currency Converter 2 (GPL) package.
  4.   Version 1.01 April 26, 2001
  5. */
  6.  
  7. // factory class
  8. function CurrencyFactory(){
  9.   this.create=create;
  10.   this.get=get;
  11.   this.getByNr=getByNr;
  12.   this.count=count;
  13.   this.getIterator=getIterator;
  14.  
  15.   this.currencies=new Array();
  16.  
  17.   // add a new currency  n=name, r=rate  
  18.   // 1 euro = 2.20 dutch guilder... so create("EUR",1)  and  create("NLG",2.20)
  19.   function create(n,r) {
  20.      this.currencies.push(new Currency(n,r));
  21.   }
  22.   // request a currency by name
  23.   function get(name){
  24.     for (i=0; i<this.currencies.length; i++) {
  25.       if (this.currencies[i].name==name)
  26.         return this.currencies[i];
  27.     }
  28.     return 0;  
  29.   }
  30.   // retrieve item by number
  31.   function getByNr(i){
  32.     return this.currencies[i];
  33.   }
  34.   // retrieve number of items
  35.   function count(){
  36.      return this.currencies.length;
  37.   }
  38.   // create Iterator
  39.   function getIterator(){
  40.     return new CurrencyIterator(this);
  41.   }
  42. }
  43.  
  44. // entity class for currencies
  45. function Currency(n,r) {
  46.   this.name=n;
  47.   this.rate=r;
  48.   
  49.   this.convertFrom=convertFrom;
  50.   // convert amount amount from currency curr to this currency
  51.   function convertFrom(curr,amount){
  52.     value=(amount * this.rate) / curr.rate;
  53.     str=(Math.round(value * 100)) / 100; // round at 2 decimals
  54.     return str;
  55.   }
  56. }
  57.  
  58. // iterator 
  59. function CurrencyIterator(cf){ 
  60.   this.first=first;
  61.   this.next=next;
  62.   this.isDone=isDone;
  63.   this.currentItem=currentItem;
  64.  
  65.   this.factory=cf;
  66.   this.counter=0;
  67.   
  68.   function first(){
  69.     this.counter=0; 
  70.   }
  71.   function next(){
  72.     this.counter++;
  73.   }
  74.   function isDone(){
  75.     return (this.counter>=cf.count());
  76.   }
  77.   function currentItem(){
  78.     return this.factory.getByNr(this.counter);
  79.   }
  80. }
  81.  
  82. function convert(newName, referenceName, referencePrice){
  83.   curr=currFac.get(newName);
  84.   referenceCurr=currFac.get(referenceName);    
  85.   var newPrice="Unknown";
  86.   if ((curr!=0) && (referenceCurr!=0)) { // if both exist then
  87.     newPrice=curr.convertFrom(referenceCurr,referencePrice);
  88.   } 
  89.   return newPrice;
  90. }
  91.  
  92. currFac=new CurrencyFactory();